<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="C++_base," />





  <link rel="alternate" href="/atom.xml" title="不知归期的故人" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.0" />






<meta name="description" content="本文用于介绍引用和指针的传递值和返回值问题，其中包括函数的值传递和引用传递、直接返回值和引用作为函数的返回值、返回函数内部new分配的内存的引用和引用。">
<meta name="keywords" content="C++_base">
<meta property="og:type" content="article">
<meta property="og:title" content="C++引用和指针">
<meta property="og:url" content="https://kusole.github.io/2019/04/17/引用和指针/index.html">
<meta property="og:site_name" content="不知归期的故人">
<meta property="og:description" content="本文用于介绍引用和指针的传递值和返回值问题，其中包括函数的值传递和引用传递、直接返回值和引用作为函数的返回值、返回函数内部new分配的内存的引用和引用。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://kusole.github.io/2019/04/17/引用和指针/指针和引用01.png">
<meta property="og:image" content="https://kusole.github.io/2019/04/17/引用和指针/指针和引用02.png">
<meta property="og:image" content="https://kusole.github.io/2019/04/17/引用和指针/指针和引用03.png">
<meta property="og:image" content="https://kusole.github.io/2019/04/17/引用和指针/指针和引用04.png">
<meta property="og:updated_time" content="2019-04-17T13:14:26.162Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="C++引用和指针">
<meta name="twitter:description" content="本文用于介绍引用和指针的传递值和返回值问题，其中包括函数的值传递和引用传递、直接返回值和引用作为函数的返回值、返回函数内部new分配的内存的引用和引用。">
<meta name="twitter:image" content="https://kusole.github.io/2019/04/17/引用和指针/指针和引用01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kusole.github.io/2019/04/17/引用和指针/"/>





  <title> C++引用和指针 | 不知归期的故人 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?124e5902fa6b3c1d89682ed1fa0441ac";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不知归期的故人</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">乘风破浪会有时，直挂云帆济沧海。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kusole.github.io/2019/04/17/引用和指针/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="刘韬">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不知归期的故人">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                C++引用和指针
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-17T08:59:15+08:00">
                2019-04-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/" itemprop="url" rel="index">
                    <span itemprop="name">C++</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文用于介绍引用和指针的传递值和返回值问题，其中包括函数的值传递和引用传递、直接返回值和引用作为函数的返回值、返回函数内部new分配的内存的引用和引用。</p>
<a id="more"></a>
<h2 id="函数的值传递和引用传递"><a href="#函数的值传递和引用传递" class="headerlink" title="函数的值传递和引用传递"></a>函数的值传递和引用传递</h2><p>本部分参考自：<a href="https://www.cnblogs.com/zjutzz/p/6818799.html" target="_blank" rel="noopener">https://www.cnblogs.com/zjutzz/p/6818799.html</a></p>
<p>C++的函数参数传递方式，可以是传值方式，也可以是传引用方式。传值的本质是：形参是实参的一份复制。传引用的本质是：形参和实参是同一个东西。<br>传值和传引用，对大多数常见类型都是适用的（就我所知）。指针、数组，它们都是数据类型的一种，没啥特殊的，因此指针作为函数参数传递时，也区分为传值和传引用两种方式。<br>例如：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">fun_1</span><span class="params">(<span class="keyword">int</span> a)</span></span>;    <span class="comment">//int类型，传值（复制产生新变量）</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">fun_2</span><span class="params">(<span class="keyword">int</span>&amp; a)</span></span>;   <span class="comment">//int类型，传引用（形参和实参是同一个东西）</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">fun_3</span><span class="params">(<span class="keyword">int</span>* arr)</span></span>; <span class="comment">//指针类型，传值（复制产生新变量）</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">fun_4</span><span class="params">(<span class="keyword">int</span>*&amp; arr)</span></span>; <span class="comment">//指针类型，传引用（形参和实参是同一个东西）</span></span><br></pre></td></tr></table></figure>
<p>如果希望通过将参数传递到函数中，进而改变变量的值（比如变量是<code>T a</code>，T表示类型)，则可以有这2种方式选择：</p>
<ol>
<li>传a的引用：<code>void myfun(T&amp; a)</code></li>
<li>传a的地址的值：<code>void myfun(T* a)</code></li>
</ol>
<h3 id="传值方式"><a href="#传值方式" class="headerlink" title="传值方式"></a>传值方式</h3><p>这是最简单的方式。形参意思是被调用函数的参数/变量，实参意思是主调函数中放到括号中的参数/变量。传值方式下，形参是实参的拷贝：重新建立了变量，变量取值和实参一样。</p>
<p>写一段测试代码，并配合gdb查看：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">swap</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> temp;</span><br><span class="line">    temp = a;</span><br><span class="line">    a = b;</span><br><span class="line">    b = temp;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; a &lt;&lt; <span class="string">" "</span> &lt;&lt; b &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> x = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> y = <span class="number">2</span>;</span><br><span class="line">    swap(x, y);</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; x &lt;&lt; <span class="string">" "</span> &lt;&lt; y &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">➜  hello-cpp git:(master) ✗ g++ -g test.cc</span><br><span class="line">➜  hello-cpp git:(master) ✗ gdb a.out </span><br><span class="line">(gdb) b main</span><br><span class="line">Breakpoint 1 at 0x4008fa: file test.cc, line 13.</span><br><span class="line">(gdb) r</span><br><span class="line">Starting program: /home/chris/work/hello-cpp/a.out </span><br><span class="line"></span><br><span class="line">Breakpoint 1, main () at test.cc:13</span><br><span class="line">13          int x = 1;</span><br><span class="line">(gdb) s</span><br><span class="line">14          int y = 2;</span><br><span class="line">(gdb) p &amp;x</span><br><span class="line"><span class="meta">$</span><span class="bash">1 = (int *) 0x7fffffffdc58</span></span><br><span class="line">(gdb) p &amp;y</span><br><span class="line"><span class="meta">$</span><span class="bash">2 = (int *) 0x7fffffffdc5c</span></span><br><span class="line">(gdb) s</span><br><span class="line">15          swap(x, y);</span><br><span class="line">(gdb) s</span><br><span class="line">swap (a=1, b=2) at test.cc:6</span><br><span class="line">6           temp = a;</span><br><span class="line">(gdb) p &amp;a</span><br><span class="line"><span class="meta">$</span><span class="bash">3 = (int *) 0x7fffffffdc2c</span></span><br><span class="line">(gdb) p &amp;b</span><br><span class="line"><span class="meta">$</span><span class="bash">4 = (int *) 0x7fffffffdc28</span></span><br><span class="line">(gdb)</span><br></pre></td></tr></table></figure>
<p>可以看到，实参x和y的值为1和2,形参a和b的值都是1和2；而x与a的地址、y与b的地址，并不相同，表明形参a和b是新建里的变量，也即<strong>实参是从形参复制了一份。这就是所谓的传值</strong>。</p>
<h3 id="传指针？其实还是传值！"><a href="#传指针？其实还是传值！" class="headerlink" title="传指针？其实还是传值！"></a>传指针？其实还是传值！</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(<span class="keyword">int</span> *p)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line">    p = &amp;a;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; p &lt;&lt; <span class="string">" "</span> &lt;&lt; *p &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> *p = <span class="literal">NULL</span>;</span><br><span class="line">    test(p);</span><br><span class="line">    <span class="keyword">if</span>(p==<span class="literal">NULL</span>)&#123;</span><br><span class="line">        <span class="built_in">cout</span> &lt;&lt; <span class="string">"指针p为NULL"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">➜  hello-cpp git:(master) ✗ g++ -g test2.cc </span><br><span class="line">➜  hello-cpp git:(master) ✗ gdb a.out </span><br><span class="line">(gdb) b main</span><br><span class="line">Breakpoint 1 at 0x4009e0: file test2.cc, line 11.</span><br><span class="line">(gdb) r</span><br><span class="line">Starting program: /home/chris/work/hello-cpp/a.out </span><br><span class="line"></span><br><span class="line">Breakpoint 1, main () at test2.cc:11</span><br><span class="line">11          int *p = NULL;</span><br><span class="line">(gdb) s</span><br><span class="line">12          test(p);</span><br><span class="line">(gdb) p p</span><br><span class="line"><span class="meta">$</span><span class="bash">1 = (int *) 0x0</span></span><br><span class="line">(gdb) p &amp;p</span><br><span class="line"><span class="meta">$</span><span class="bash">2 = (int **) 0x7fffffffdc58</span></span><br><span class="line">(gdb) s</span><br><span class="line">test (p=0x0) at test2.cc:4</span><br><span class="line">4       void test(int *p)&#123;</span><br><span class="line">(gdb) s</span><br><span class="line">5           int a = 1;</span><br><span class="line">(gdb) p p</span><br><span class="line"><span class="meta">$</span><span class="bash">3 = (int *) 0x0</span></span><br><span class="line">(gdb) p &amp;p</span><br><span class="line"><span class="meta">$</span><span class="bash">4 = (int **) 0x7fffffffdc18</span></span><br><span class="line">(gdb)</span><br></pre></td></tr></table></figure>
<p>可以看到，<code>main()</code>函数内和<code>test()</code>函数内，变量p的值都是0,也就是都是空指针；但是它们的地址是不同的。也就是说，形参p只是从形参p那里复制了一份值（空指针的取值），形参是新创建的变量。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">➜  hello-cpp git:(master) ✗ ./a.out </span><br><span class="line">0x7fff2a329e24 1</span><br><span class="line">指针p为NULL</span><br></pre></td></tr></table></figure>
<h3 id="传引用"><a href="#传引用" class="headerlink" title="传引用"></a>传引用</h3><p>传值是C和C++都能用的方式。传引用则是C++比C所不同的地方。<strong>传引用，传递的是实参本身，而不是实参的一个拷贝，形参的修改就是实参的修改</strong>。相比于传值，传引用的好处是省去了复制，节约了空间和时间。假如不希望修改变量的值，那么请选择传值而不是传引用。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(<span class="keyword">int</span> &amp;a)</span></span>&#123;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; &amp;a &lt;&lt; <span class="string">" "</span> &lt;&lt; a &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; &amp;a &lt;&lt; <span class="string">" "</span> &lt;&lt; a &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    test(a);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">➜  hello-cpp git:(master) ✗ ./a.out</span><br><span class="line">0x7ffec97399e4 1</span><br><span class="line">0x7ffec97399e4 1</span><br></pre></td></tr></table></figure>
<p>显然，形参a和实参a完全一样：值相同，地址也相同。说明形参不是实参的拷贝，而是就是实参本身。</p>
<h3 id="实现swap-函数"><a href="#实现swap-函数" class="headerlink" title="实现swap()函数"></a>实现swap()函数</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myswap_pass_by_reference</span><span class="params">(<span class="keyword">int</span>&amp; a, <span class="keyword">int</span> &amp;b)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> t = a;</span><br><span class="line">    a = b;</span><br><span class="line">    b = t;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myswap_pass_by_pointer_value</span><span class="params">(<span class="keyword">int</span>* a, <span class="keyword">int</span>* b)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> t = *a;</span><br><span class="line">    *a = *b;</span><br><span class="line">    *b = t;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a=<span class="number">1</span>, b=<span class="number">2</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"originally"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"a="</span> &lt;&lt; a &lt;&lt; <span class="string">", b="</span> &lt;&lt; b &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"></span><br><span class="line">    myswap_pass_by_reference(a, b);</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"after myswap_pass_by_reference"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"a="</span> &lt;&lt; a &lt;&lt; <span class="string">", b="</span> &lt;&lt; b &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"></span><br><span class="line">    myswap_pass_by_pointer_value(&amp;a, &amp;b);</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"after myswap_pass_by_pointer_value"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"a="</span> &lt;&lt; a &lt;&lt; <span class="string">", b="</span> &lt;&lt; b &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序执行结果：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">originally</span><br><span class="line">a=1, b=2</span><br><span class="line">after myswap_pass_by_reference</span><br><span class="line">a=2, b=1</span><br><span class="line">after myswap_pass_by_pointer_value</span><br><span class="line">a=1, b=2</span><br></pre></td></tr></table></figure>
<h3 id="真的理解了吗？"><a href="#真的理解了吗？" class="headerlink" title="真的理解了吗？"></a>真的理解了吗？</h3><p>其实出问题最多的还是指针相关的东西。指针作为值传递是怎样用的？指针作为引用传递又是怎样用的？</p>
<p>首先要明确，“引用”类型变量的声明方式：<code>变量类型 &amp; 变量名</code>。<br>“指针”类型的声明方式：<code>基类型* 变量名</code>。<br>所以，“指针的引用类型”应当这样声明：<code>基类型*&amp; 变量名</code>。</p>
<p>这样看下来，不要把指针类型看得那么神奇，而是把它看成一种数据类型，那么事情就简单了：指针类型，也是有传值、传引用两种函数传参方式的。</p>
<p>指针的传值</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>* a, <span class="keyword">int</span> n)</span></span></span><br></pre></td></tr></table></figure>
<p>指针的传引用</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>*&amp; arr, <span class="keyword">int</span> n)</span></span></span><br></pre></td></tr></table></figure>
<h3 id="使用函数模版"><a href="#使用函数模版" class="headerlink" title="使用函数模版"></a>使用函数模版</h3><p>考虑这样一个问题：写一个函数，遍历输出一个一维数组的各个元素。<br>第一种方法，数组退化为指针，传值。同时还需要另一个参数来指定数组长度：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">traverse_1d_array</span><span class="params">(<span class="keyword">int</span>* arr, <span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>缺点是需要指定n的大小。以及，传值会产生复制，如果大量执行这个函数会影响性能。<br>另一种方式，传入参数是数组的引用。想到的写法，需要事先知道数组长度：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">void traverse_1d_array(int (&amp;arr)[10])&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>缺点是需要在函数声明的时候就确定好数组的长度。这很受限。<br>还有一种方法。使用模板函数，来接受任意长度的数组：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">size_t</span> size&gt;</span><br><span class="line">void fun(int (&amp;arr)[size])&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这种使用模板声明数组长度的方式很方便，当调用函数时，编译器从数组实参计算出数组长度。也就是说，不用手工指定数组长度，让编译器自己去判断。这很方便啊。用这种方式，随手写一个2维数组的遍历输出函数：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">size_t</span> m, <span class="keyword">size_t</span> n&gt;</span><br><span class="line">void traverse_array_2d(int (&amp;arr)[m][n])&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;m; i++)&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">0</span>; j&lt;n; j++)&#123;</span><br><span class="line">            <span class="built_in">cout</span> &lt;&lt; arr[i][j] &lt;&lt; <span class="string">","</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">cout</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>普通类型，以<code>int a</code>为例：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span> a)</span>    <span class="comment">//传值，产生复制</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>&amp; a)</span>   <span class="comment">//传引用，不产生复制</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>* a)</span>   <span class="comment">//传地址，产生复制，本质上是一种传值，这个值是地址</span></span></span><br></pre></td></tr></table></figure>
<p>指针类型，以<code>int* a</code>为例：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>* a)</span>   <span class="comment">//传值，产生复制</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>*&amp; a)</span>  <span class="comment">//传引用，不产生复制</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>** a)</span>   <span class="comment">//传地址，产生复制，本质上是一种传值，这个值是指针的地址</span></span></span><br></pre></td></tr></table></figure>
<p>数组类型，以<code>int a[10]</code>为例：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span> a[], <span class="keyword">int</span> n)</span> <span class="comment">//传值，产生复制</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">myfun</span><span class="params">(<span class="keyword">int</span>* a, <span class="keyword">int</span> n)</span> <span class="comment">//传值，产生复制，传递的数组首地址</span></span></span><br><span class="line">void myfun(int (&amp;arr)[10]) //传引用，不产生复制。需要硬编码数组长度</span><br><span class="line">template&lt;size_t size&gt; void myfun(int (&amp;arr)[size]) //传引用，不产生复制。不需要硬编码数组长度</span><br></pre></td></tr></table></figure>
<h2 id="返回值和返回引用"><a href="#返回值和返回引用" class="headerlink" title="返回值和返回引用"></a>返回值和返回引用</h2><p>本部分参考：</p>
<p>[1] <a href="https://blog.csdn.net/weixin_40539125/article/details/81410008#commentBox" target="_blank" rel="noopener">https://blog.csdn.net/weixin_40539125/article/details/81410008#commentBox</a></p>
<p>[2] <a href="https://www.cnblogs.com/fly1988happy/archive/2011/12/14/2286908.html" target="_blank" rel="noopener">https://www.cnblogs.com/fly1988happy/archive/2011/12/14/2286908.html</a></p>
<p>[3] <a href="https://www.cnblogs.com/duwenxing/p/7421100.html" target="_blank" rel="noopener">https://www.cnblogs.com/duwenxing/p/7421100.html</a></p>
<p>引用作为返回值：</p>
<p><strong>语法：类型 &amp;函数名（形参列表）{ 函数体 }</strong></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">float</span> temp;</span><br><span class="line"><span class="function"><span class="keyword">float</span> <span class="title">fn1</span><span class="params">(<span class="keyword">float</span> r)</span></span>&#123;</span><br><span class="line">    temp=r*r*<span class="number">3.14</span>;</span><br><span class="line">    <span class="keyword">return</span> temp;</span><br><span class="line">&#125; </span><br><span class="line"><span class="function"><span class="keyword">float</span> &amp;<span class="title">fn2</span><span class="params">(<span class="keyword">float</span> r)</span></span>&#123; <span class="comment">//&amp;说明返回的是temp的引用，换句话说就是返回temp本身</span></span><br><span class="line">    temp=r*r*<span class="number">3.14</span>;</span><br><span class="line">    <span class="keyword">return</span> temp;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">float</span> a=fn1(<span class="number">5.0</span>); <span class="comment">//case 1：返回值</span></span><br><span class="line">    <span class="comment">//float &amp;b=fn1(5.0); //case 2:用函数的返回值作为引用的初始化值 [Error] invalid initialization of non-const reference of type 'float&amp;' from an rvalue of type 'float'</span></span><br><span class="line">                           <span class="comment">//（有些编译器可以成功编译该语句，但会给出一个warning） </span></span><br><span class="line">    <span class="keyword">float</span> c=fn2(<span class="number">5.0</span>);<span class="comment">//case 3：返回引用</span></span><br><span class="line">    <span class="keyword">float</span> &amp;d=fn2(<span class="number">5.0</span>);<span class="comment">//case 4：用函数返回的引用作为新引用的初始化值</span></span><br><span class="line">    <span class="built_in">cout</span>&lt;&lt;a&lt;&lt;<span class="built_in">endl</span>;<span class="comment">//78.5</span></span><br><span class="line">    <span class="comment">//cout&lt;&lt;b&lt;&lt;endl;//78.5</span></span><br><span class="line">    <span class="built_in">cout</span>&lt;&lt;c&lt;&lt;<span class="built_in">endl</span>;<span class="comment">//78.5</span></span><br><span class="line">    <span class="built_in">cout</span>&lt;&lt;d&lt;&lt;<span class="built_in">endl</span>;<span class="comment">//78.5</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="case-1：用返回值方式调用函数"><a href="#case-1：用返回值方式调用函数" class="headerlink" title="case 1：用返回值方式调用函数"></a>case 1：用返回值方式调用函数</h3><p><img src="/2019/04/17/引用和指针/指针和引用01.png" alt=""></p>
<p>返回全局变量temp的值时，C++会在内存中创建临时变量并将temp的值拷贝给该临时变量。当返回到主函数main后，赋值语句a=fn1(5.0)会把临时变量的值再拷贝给变量a</p>
<h3 id="case-2：用函数的返回值初始化引用的方式调用函数"><a href="#case-2：用函数的返回值初始化引用的方式调用函数" class="headerlink" title="case 2：用函数的返回值初始化引用的方式调用函数"></a>case 2：用函数的返回值初始化引用的方式调用函数</h3><p><img src="/2019/04/17/引用和指针/指针和引用02.png" alt=""></p>
<p>这种情况下，函数fn1()是以值方式返回到，返回时，首先拷贝temp的值给临时变量。返回到主函数后，用临时变量来初始化引用变量b，使得b成为该临时变量到的别名。由于临时变量的作用域短暂（在C++标准中，临时变量或对象的生命周期在一个完整的语句表达式结束后便宣告结束，也就是在语句float &amp;b=fn1(5.0);之后） ，所以b面临无效的危险，很有可能以后的值是个无法确定的值。</p>
<p> <strong>如果真的希望用函数的返回值来初始化一个引用，应当先创建一个变量，将函数的返回值赋给这个变量，然后再用该变量来初始化引用：</strong></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> x=fn1(<span class="number">5.0</span>);</span><br><span class="line"><span class="keyword">int</span> &amp;b=x;</span><br></pre></td></tr></table></figure>
<h3 id="case-3：用返回引用的方式调用函数"><a href="#case-3：用返回引用的方式调用函数" class="headerlink" title="case 3：用返回引用的方式调用函数"></a>case 3：用返回引用的方式调用函数</h3><p><img src="/2019/04/17/引用和指针/指针和引用03.png" alt=""></p>
<p>这种情况下，函数fn2()的返回值不产生副本，而是直接将变量temp返回给主函数，即主函数的赋值语句中的左值是直接从变量temp中拷贝而来（也就是说c只是变量temp的一个拷贝而非别名） ，这样就避免了临时变量的产生。尤其当变量temp是一个用户自定义的类的对象时，这样还避免了调用类中的拷贝构造函数在内存中创建临时对象的过程，提高了程序的时间和空间的使用效率。</p>
<h3 id="case-4：用函数返回的引用作为新引用的初始化值的方式来调用函数"><a href="#case-4：用函数返回的引用作为新引用的初始化值的方式来调用函数" class="headerlink" title="case 4：用函数返回的引用作为新引用的初始化值的方式来调用函数"></a>case 4：用函数返回的引用作为新引用的初始化值的方式来调用函数</h3><p><img src="/2019/04/17/引用和指针/指针和引用04.png" alt=""></p>
<p>这种情况下，函数fn2()的返回值不产生副本，而是直接将变量temp返回给主函数。在主函数中，一个引用声明d用该返回值初始化，也就是说此时d成为变量temp的别名。由于temp是全局变量，所以在d的有效期内temp始终保持有效，故这种做法是安全的。</p>
<h3 id="注意几点！！！"><a href="#注意几点！！！" class="headerlink" title="注意几点！！！"></a>注意几点！！！</h3><p>1.引用作为函数的返回值时，<strong>必须在定义函数时在函数名前将&amp;</strong></p>
<p>2.用引用作函数的返回值的<strong>最大的好处是在内存中不产生返回值的副本</strong></p>
<p>3.<strong>不能返回局部变量的引用。</strong>如上面的例子，如果temp是局部变量，那么它会在函数返回后被销毁，此时对temp的引用就会成为“无所指”的引用，程序会进入未知状态。</p>
<p>​    具体参见：<a href="https://bbs.csdn.net/topics/350254894" target="_blank" rel="noopener">https://bbs.csdn.net/topics/350254894</a></p>
<p>4.<strong>不能返回函数内部通过new分配的内存的引用</strong>。虽然不存在局部变量的被动销毁问题，但如果被返回的函数的引用只是作为一个临时变量出现，而没有将其赋值给一个实际的变量，那么就可能造成这个引用所指向的空间（有new分配）无法释放的情况（由于没有具体的变量名，故无法用delete手动释放该内存），从而造成内存泄漏。因此应当避免这种情况的发生</p>
<p>5.<strong>当返回类成员的引用时，最好是const引用</strong>。这样可以避免在无意的情况下破坏该类的成员。</p>
<p>​    具体参见：<a href="https://blog.csdn.net/dearwind153/article/details/51926746" target="_blank" rel="noopener">https://blog.csdn.net/dearwind153/article/details/51926746</a></p>
<p>6.可以用函数返回的引用作为赋值表达式中的左值</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">int</span> value[<span class="number">10</span>];</span><br><span class="line"><span class="keyword">int</span> error=<span class="number">-1</span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> &amp;<span class="title">func</span><span class="params">(<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(n&gt;=<span class="number">0</span>&amp;&amp;n&lt;=<span class="number">9</span>)</span><br><span class="line">        <span class="keyword">return</span> value[n];<span class="comment">//返回的引用所绑定的变量一定是全局变量，不能是函数中定义的局部变量 </span></span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="keyword">return</span> error;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    func(<span class="number">0</span>)=<span class="number">10</span>;</span><br><span class="line">    func(<span class="number">4</span>)=<span class="number">12</span>;</span><br><span class="line">    <span class="built_in">cout</span>&lt;&lt;value[<span class="number">0</span>]&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">cout</span>&lt;&lt;value[<span class="number">4</span>]&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="用引用实现多态"><a href="#用引用实现多态" class="headerlink" title="用引用实现多态"></a>用引用实现多态</h3><p>在C++中，<strong>引用是除了指针外另一个可以产生多态效果的手段</strong>。也就是说一个基类的引用可以用来绑定其派生类的实例</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Father</span>;</span><span class="comment">//基类（父类）</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Son</span>：<span class="title">public</span> <span class="title">Father</span>&#123;</span>.....&#125;<span class="comment">//Son是Father的派生类</span></span><br><span class="line">Son son;<span class="comment">//son是类Son的一个实例</span></span><br><span class="line">Father &amp;ptr=son;<span class="comment">//用派生类的对象初始化基类对象的使用</span></span><br></pre></td></tr></table></figure>
<p><strong>特别注意：</strong></p>
<p><strong>ptr只能用来访问派生类对象中从基类继承下来的成员</strong>。<strong>如果基类（类Father）中定义的有虚函数，那么就可以通过在派生类（类Son）中重写这个虚函数来实现类的多态。</strong></p>
<h3 id="常引用"><a href="#常引用" class="headerlink" title="常引用"></a>常引用</h3><p><strong>常引用不允许通过该引用对其所绑定的变量或对象进行修改</strong></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a=<span class="number">10</span>;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> &amp;new_a=a;</span><br><span class="line">    new_a=<span class="number">11</span>;<span class="comment">//错误！不允许通过常引用对其所绑定的变量或对象进行修改 </span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;string&gt; </span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="built_in">string</span> <span class="title">func1</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="built_in">string</span> temp=<span class="string">"This is func1"</span>;</span><br><span class="line">    <span class="keyword">return</span> temp;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">func2</span><span class="params">(<span class="built_in">string</span> &amp;str)</span></span>&#123;</span><br><span class="line">    <span class="built_in">cout</span>&lt;&lt;str&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">void func2(const string &amp;str)&#123;</span></span><br><span class="line"><span class="comment">    cout&lt;&lt;str&lt;&lt;endl;</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    func2(func1());</span><br><span class="line">    func2(<span class="string">"Tomwenxing"</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是由于func1()和“Tomwenxing”都会在系统中产生一个临时对象（string对象）来存储它们，而<strong>在C++中所有的临时对象都是const类型的</strong>，而上面的程序试图将const对象赋值给非const对象，这必然会使程序报错。如果在函数func2的参数前添加const，则程序便可正常运行了</p>
<h3 id="关于返回函数内部new分配的内存的引用"><a href="#关于返回函数内部new分配的内存的引用" class="headerlink" title="关于返回函数内部new分配的内存的引用"></a>关于返回函数内部new分配的内存的引用</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="built_in">string</span>&amp; <span class="title">foo</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">string</span>* str = <span class="keyword">new</span> <span class="built_in">string</span>(<span class="string">"abc"</span>);</span><br><span class="line">    <span class="keyword">return</span> *str; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>非法的，为什么？</p>
<p>其实，不能说这是非法的，只能说这种u编程习惯很不好，这样很可能造成内存泄露。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">a_s</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">int</span> a;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function">a_s* <span class="title">foo</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">a_s</span>* <span class="title">sp</span> = <span class="title">new</span> <span class="title">struct</span> <span class="title">a_s</span>;</span></span><br><span class="line">    <span class="keyword">return</span> sp;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//这个挺好啊，为什么换成reference就泄漏了？</span></span><br></pre></td></tr></table></figure>
<p>如果按照以上两种做法，即使很小心的程序员也难免会造成内存泄露。</p>
<p>比如：string str = foo(); 显然new生成的这块内存将无法释放。</p>
<p>只能这样：</p>
<p>string&amp; tmp = foo();<br>string str = tmp;<br>delete &tmp;</p>
<p>参考：<a href="https://blog.csdn.net/why_ny/article/details/7901670" target="_blank" rel="noopener">https://blog.csdn.net/why_ny/article/details/7901670</a></p>
<h3 id="引用返回值为需要传入的引用的对象"><a href="#引用返回值为需要传入的引用的对象" class="headerlink" title="引用返回值为需要传入的引用的对象"></a>引用返回值为需要传入的引用的对象</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//正确的方式</span></span><br><span class="line"><span class="function"><span class="keyword">int</span>&amp; <span class="title">abc</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b, <span class="keyword">int</span> c, <span class="keyword">int</span>&amp; result)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    result = a + b + c;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//错误的方式</span></span><br><span class="line"><span class="function"><span class="keyword">int</span>&amp; <span class="title">abc</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b, <span class="keyword">int</span> c)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b + c;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//两种调用方式</span></span><br><span class="line"><span class="keyword">int</span> &amp;x=abc(...)<span class="comment">//不会产生复制</span></span><br><span class="line"><span class="keyword">int</span> x=abc(...)<span class="comment">//会产生复制</span></span><br></pre></td></tr></table></figure>
<h3 id="返回const类型"><a href="#返回const类型" class="headerlink" title="返回const类型"></a>返回const类型</h3><p>由于返回值直接指向了一个生命期尚未结束的变量，因此，对于函数返回值（或者称为函数结果）本身的任何操作，都在实际上，是对那个变量的操作，这就是引入const类型的返回的意义。当使用了const关键字后，即意味着函数的返回值不能立即得到修改！如下代码，将无法编译通过，这就是因为返回值立即进行了++操作（相当于对变量z进行了++操作），而这对于该函数而言，是不允许的。如果去掉const，再行编译，则可以获得通过，并且打印形成z = 7的结果。 </p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">include &lt;iostream&gt;</span><br><span class="line">include &lt;cstdlib&gt;</span><br><span class="line"><span class="function"><span class="keyword">const</span> <span class="keyword">int</span>&amp; <span class="title">abc</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b, <span class="keyword">int</span> c, <span class="keyword">int</span>&amp; result)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    result = a + b + c;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="keyword">int</span> a = <span class="number">1</span>; <span class="keyword">int</span> b = <span class="number">2</span>; <span class="keyword">int</span> c=<span class="number">3</span>;</span><br><span class="line">   <span class="keyword">int</span> z;</span><br><span class="line">   abc(a, b, c, z)++;  <span class="comment">//wrong: returning a const reference</span></span><br><span class="line">   <span class="built_in">cout</span> &lt;&lt; <span class="string">"z= "</span> &lt;&lt; z &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">   <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">int</span> j=<span class="number">3</span>;<span class="comment">//j是全局变量</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">val</span><span class="params">()</span> </span></span><br><span class="line"><span class="function"></span>&#123; </span><br><span class="line"></span><br><span class="line">     <span class="keyword">int</span> i = <span class="number">1</span>; </span><br><span class="line">     <span class="keyword">return</span> i; </span><br><span class="line">&#125; </span><br><span class="line"><span class="function"><span class="keyword">int</span> &amp; <span class="title">ref</span><span class="params">()</span> </span></span><br><span class="line"><span class="function"></span>&#123; </span><br><span class="line"><span class="comment">//   int j=3;j不能是局部变量！</span></span><br><span class="line">    <span class="keyword">int</span> &amp;i = j; </span><br><span class="line">      <span class="keyword">return</span> i; <span class="comment">//不能返回局部对象的引用</span></span><br><span class="line">&#125; </span><br><span class="line">  </span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span> </span></span><br><span class="line"><span class="function"></span>&#123; </span><br><span class="line"></span><br><span class="line">      <span class="keyword">int</span>   vv = val(); </span><br><span class="line">      <span class="keyword">int</span>   rv = val();<span class="comment">//int   &amp;rv = val()错误！引用指向临时变量，为临时变量的别名</span></span><br><span class="line">      <span class="keyword">int</span>   vr = ref(); </span><br><span class="line">      <span class="keyword">int</span> &amp; rr = ref(); </span><br><span class="line">      <span class="built_in">cout</span>&lt;&lt;vv&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">      <span class="built_in">cout</span>&lt;&lt;rv&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">      <span class="built_in">cout</span>&lt;&lt;vr&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">      <span class="built_in">cout</span>&lt;&lt;rr&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">      <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="拷贝构造与引用"><a href="#拷贝构造与引用" class="headerlink" title="拷贝构造与引用"></a>拷贝构造与引用</h2><p>看下面的函数，返回的是t而不是&amp;t，所以一定会有临时变量产生。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">T function1()&#123;</span><br><span class="line">    T t(0);</span><br><span class="line">    return t;</span><br><span class="line">&#125;</span><br><span class="line">T x=function1();</span><br></pre></td></tr></table></figure>
<p>这里的过程是：<br>1.创建命名对象t<br>2.拷贝构造一个无名的临时对象，并返回这个临时对象<br>3.由临时对象拷贝构造对象x<br>4.T x=function1();这句语句结束时，析构临时对象<br>这里一共生成了3个对象，一个命名对象t，一个临时对象作为返回值，一个命名对象x。</p>
<p>下面的函数稍微复杂一定，它没有先定义一个中间变量t，看起来似乎是直接返回了一个临时变量。但实际上，如果不经过c++的优化，那么它并没有提高效率，因为它还是创建了3个对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">T function2()&#123;</span><br><span class="line">     return T(0);</span><br><span class="line">&#125;</span><br><span class="line">T x=function2();</span><br></pre></td></tr></table></figure>
<p>  这里的过程是：<br>1.创建一个无名对象<br>2.由无名对象拷贝构造一个无名的临时对象<br>3.析构无名对象，返回临时对象<br>4.由临时对象拷贝构造对象x<br>5.T x=function2()语句结束时，析构临时对象。<br>这里一共生成了3个对象，其中有2个对象都是马上被析构掉的，不能被后面的代码使用。既然是这样，那么就会有优化的余地，可以尝试着不要前面的两个临时变量。c++确实会做这样的优化，优化后的c++会避免匿名对象和临时对象这两个对象的生成，而直接生成x，这样就减少了两次对象生成-回收的消耗，提高了程序性能。</p>
<p>其实function1()这段代码也是会经过优化的，但因为临时对象t是一个命名对象，所以一定会被创建。存储返回值的临时对象是多余的，会被优化掉而不生成。<br>但是，程序员不应该依赖这种优化，因为c++不保证这种优化一定会做。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>如果文章对您有帮助，请随意打赏</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="https://i.loli.net/2018/10/15/5bc436827b4bc.png" alt="刘韬 WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="https://i.loli.net/2018/10/15/5bc4368266e2b.png" alt="刘韬 Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/C-base/" rel="tag"># C++_base</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/02/NCbstree/" rel="next" title="[牛客网算法]--二叉树">
                <i class="fa fa-chevron-left"></i> [牛客网算法]--二叉树
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.png"
               alt="刘韬" />
          <p class="site-author-name" itemprop="name">刘韬</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">26</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/kusole" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.douban.com/people/83381421/" target="_blank" title="豆瓣">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  豆瓣
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/liu-tao-86-26-47/activities" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  知乎
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/6193724399/profile?topnav=1&wvr=6&is_all=1" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#函数的值传递和引用传递"><span class="nav-number">1.</span> <span class="nav-text">函数的值传递和引用传递</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#传值方式"><span class="nav-number">1.1.</span> <span class="nav-text">传值方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#传指针？其实还是传值！"><span class="nav-number">1.2.</span> <span class="nav-text">传指针？其实还是传值！</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#传引用"><span class="nav-number">1.3.</span> <span class="nav-text">传引用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实现swap-函数"><span class="nav-number">1.4.</span> <span class="nav-text">实现swap()函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#真的理解了吗？"><span class="nav-number">1.5.</span> <span class="nav-text">真的理解了吗？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用函数模版"><span class="nav-number">1.6.</span> <span class="nav-text">使用函数模版</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">1.7.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#返回值和返回引用"><span class="nav-number">2.</span> <span class="nav-text">返回值和返回引用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#case-1：用返回值方式调用函数"><span class="nav-number">2.1.</span> <span class="nav-text">case 1：用返回值方式调用函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#case-2：用函数的返回值初始化引用的方式调用函数"><span class="nav-number">2.2.</span> <span class="nav-text">case 2：用函数的返回值初始化引用的方式调用函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#case-3：用返回引用的方式调用函数"><span class="nav-number">2.3.</span> <span class="nav-text">case 3：用返回引用的方式调用函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#case-4：用函数返回的引用作为新引用的初始化值的方式来调用函数"><span class="nav-number">2.4.</span> <span class="nav-text">case 4：用函数返回的引用作为新引用的初始化值的方式来调用函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注意几点！！！"><span class="nav-number">2.5.</span> <span class="nav-text">注意几点！！！</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用引用实现多态"><span class="nav-number">2.6.</span> <span class="nav-text">用引用实现多态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常引用"><span class="nav-number">2.7.</span> <span class="nav-text">常引用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#关于返回函数内部new分配的内存的引用"><span class="nav-number">2.8.</span> <span class="nav-text">关于返回函数内部new分配的内存的引用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引用返回值为需要传入的引用的对象"><span class="nav-number">2.9.</span> <span class="nav-text">引用返回值为需要传入的引用的对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回const类型"><span class="nav-number">2.10.</span> <span class="nav-text">返回const类型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#拷贝构造与引用"><span class="nav-number">3.</span> <span class="nav-text">拷贝构造与引用</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">刘韬</span>

</div>


<div class="Hosted-by">
  由 <a class="theme-link" href="https://pages.github.com/">GitHub Pages</a> 强力驱动
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

<!-- <div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

-->


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>





  

  

  
  


  

</body>
</html>
